exports.salesPerformanceStatistics = (req, res) => {

    var restfulParams = req.routeInfo.restfulParams;

    var resultData = {};

    var startAndEndTime = common.getAppointBeginningEndTime(restfulParams.year, restfulParams.month);

    var monthStart = startAndEndTime.firstDate;

    var monthEnd = startAndEndTime.endDate;

    var is_manager = restfulParams.is_manager;

    var u_type = restfulParams.u_type;

    var u_osid = restfulParams.os_id;

    console.log("----------------------->")

    //销售员列表
    function salesmanList(cb) {

        //根据当前用户类型获取所显示的销售列表
        var url = "";
        //平台管理，战略管理，代理商管理
        //是管理，则查询该节点下的所有组长
        if (is_manager == '1' && (u_type == '1' || u_type == '2')) {
            url = CORE_APIConfig.coreAPI.userSearch.Request_Api_Url + "/u_is_delete/0/u_master_osid/" + restfulParams.os_id + "/u_type/3/u_is_manager/1/skip/0/limit/9999"
        } else if (is_manager == '1' && u_type == '3') {
            url = CORE_APIConfig.coreAPI.userSearch.Request_Api_Url + "/u_is_delete/0/u_leader/" + restfulParams.u_id + "/skip/0/limit/9999"
        } else {
            url = CORE_APIConfig.coreAPI.userSearch.Request_Api_Url + "/u_is_delete/0/u_leader/" + restfulParams.u_leader + "/skip/0/limit/9999"
        }

        R.SEND_HTTP(
            req,
            res,
            {
                url: url,
                method: 'POST',
                data: {
                    fields: ['u_id', 'u_nickname', 'u_type', 'u_leader', 'u_is_manager', 'u_master_osid'].join(",")
                }
            },
            function (data) {


                // resultData.salesmanList = data.result.data;

                // return RES.successResponse(res, resultData);
                var memberData = data.result.data;

                var salesmanList = [];

                for (var i = 0; i < memberData.length; i++) {
                    if (memberData[i].u_is_admin != 1) {
                        salesmanList.push(memberData[i])
                    }
                }

                resultData.salesmanList = salesmanList;

                cb();

            }
        )
    }

    //查询每个员工下级销售
    function searchUnderSales(cb) {

        F.ParallelEach(resultData.salesmanList, function (item, index, callback) {
            //
            function underSalesList(eachCb) {

                if (item.u_is_manager == 1 && (item.u_type == 1 || item.u_type == 2)) {
                    //战略  查询战略伙伴下所有销售
                    console.log("战略 || 代理");
                    R.SEND_HTTP(
                        req,
                        res, {
                            url: CORE_APIConfig.coreAPI.userSearch.Request_Api_Url + "/u_master_osid/" + item.u_master_osid,
                            method: 'POST',
                            data: {
                                fields: ['u_id'].join(",")
                            }
                        },
                        function (data) {

                            item.salesArr = data.result.data;

                            eachCb();

                        }
                    )
                } else if (item.u_is_manager == 1 && item.u_type == 3) {
                    //销售主管  查询该销售主管下所有销售.包括自己。
                    console.log("销售组长");

                    R.SEND_HTTP(
                        req,
                        res, {
                            url: CORE_APIConfig.coreAPI.userSearch.Request_Api_Url + "/u_leader/" + item.u_id,
                            method: 'POST',
                            data: {
                                fields: ['u_id'].join(",")
                            }
                        },
                        function (data) {

                            item.salesArr = data.result.data;

                            eachCb();

                        }
                    )
                } else if (item.u_is_manager == 0 && item.u_type == 3) {
                    //普通销售
                    console.log("普通销售");
                    item.salesArr = [{
                        u_id: item.u_id
                    }];
                    eachCb();
                } else if (item.u_type == 0) {
                    //超管
                    console.log("超管");
                    R.SEND_HTTP(
                        req,
                        res, {
                            url: CORE_APIConfig.coreAPI.userSearch.Request_Api_Url,
                            method: 'POST',
                            data: {
                                fields: ['u_id'].join(",")
                            }
                        },
                        function (data) {

                            item.salesArr = data.result.data;

                            eachCb();

                        }
                    )
                }
            }


            F.Parallel([
                underSalesList
            ], () => {
                callback();
            })

        }, cb)

    }

    //查询每个销售当月的销售总额、新增客户人数、跟进总数、成交总数
    function queryForEachSalesRelated(cb) {

        F.ParallelEach(resultData.salesmanList, function (item, index, callback) {
            var totalSales = 0;//销售总额
            var totalMonthlyTurnover = 0;//月成交量
            var salesBeReadCount = 0;//阅读数
            var numberAddedInTheMonth = 0;//当月新增数量
            var totalMonthlyFollowUp = 0;//当月跟进数

            function queryForEachSalesData(cb) {
                item.is_group_leader = 0;
                if (restfulParams.u_leader > 0 && item.u_id == restfulParams.u_leader) {
                    item.salesArr = [{
                        u_id: restfulParams.u_leader
                    }];
                    item.is_group_leader = 1;
                }

                F.ParallelEach(item.salesArr, function (underItem, underIndex, underCallback) {
                    //查询当月销售总额+月成交数量


                    function totalMonthlySales(eachCb) {

                        R.SEND_HTTP(
                            req,
                            res,
                            {
                                url: config.external_server.apiAddress + "/organization/search_art_product_order/apo_status/1/apo_invite_code/" + underItem.u_id + "/between/" + monthStart + "-apo_create_time-" + monthEnd,
                                method: 'POST',
                                data: {
                                    fields: ['apo_real_pay'].join(",")
                                }
                            },
                            function (data) {

                                var realPayData = data.result.data;
                                var totalSalesSingle = 0;

                                for (var i = 0; i < realPayData.length; i++) {
                                    totalSalesSingle += parseFloat(realPayData[i].apo_real_pay)
                                }

                                totalSales += parseFloat(totalSalesSingle);

                                totalMonthlyTurnover += parseInt(realPayData.length);


                                eachCb();

                            }
                        )
                    }

                    //查询当月销售阅读数
                    function salesBeRead(eachCb) {

                        R.SEND_HTTP(
                            req,
                            res,
                            {
                                url: config.external_server.apiAddress + "/organization/search_art_product_user_read_record/count/1/apurr_uid/" + underItem.u_id + "/between/" + monthStart + "-apurr_create_time-" + monthEnd,
                                method: 'POST'
                            },
                            function (data) {

                                salesBeReadCount += parseInt(data.result.count);

                                eachCb();

                            }
                        )
                    }

                    //查询当月新增人数
                    function numberAddedThisMonth(eachCb) {

                        R.SEND_HTTP(
                            req,
                            res,
                            {
                                url: CORE_APIConfig.coreAPI.artCustomerSearch.Request_Api_Url + "/count/1/c_is_delete/0/c_uid/" + underItem.u_id + "/between/" + monthStart + "-c_create_time-" + monthEnd,
                                method: 'POST',
                                data: {
                                    fields: ['c_id'].join(",")
                                }
                            },
                            function (data) {


                                numberAddedInTheMonth += parseInt(data.result.count);
                                eachCb();

                            }
                        )
                    }

                    //查询当月跟进总数
                    function thisMonthFollowUp(eachCb) {

                        R.SEND_HTTP(
                            req,
                            res,
                            {
                                url: CORE_APIConfig.coreAPI.artCustomerFollowRecordSearch.Request_Api_Url + "/count/1/cfr_is_delete/0/cfr_uid/" + underItem.u_id + "/between/" + monthStart + "-cfr_create_time-" + monthEnd + "/sort_order/cfr_cid-desc",
                                method: 'POST',
                                data: {
                                    fields: ['cfr_cid'].join(",")
                                }
                            },
                            function (data) {

                                var followUpData = data.result.data;

                                var thisFollowUp = [];

                                if (followUpData.length > 0) {
                                    thisFollowUp = [followUpData[0]];

                                    for (let i = 1; i < followUpData.length; i++) {
                                        let repeat = false;
                                        for (let j = 0; j < thisFollowUp.length; j++) {
                                            if (followUpData[i].cfr_cid === thisFollowUp[j].cfr_cid) {
                                                repeat = true;
                                                break;
                                            } else {

                                            }
                                        }
                                        if (!repeat) {
                                            thisFollowUp.push(followUpData[i]);
                                        }
                                    }

                                }

                                totalMonthlyFollowUp += parseInt(thisFollowUp.length);
                                eachCb();

                            }
                        )

                    }

                    F.Parallel([
                        totalMonthlySales,
                        salesBeRead,
                        numberAddedThisMonth,
                        thisMonthFollowUp,
                    ], () => {
                        item.totalSales = totalSales.toFixed(2);
                        item.totalMonthlyTurnover = totalMonthlyTurnover;
                        item.salesBeReadCount = salesBeReadCount;
                        item.numberAddedInTheMonth = numberAddedInTheMonth;
                        item.totalMonthlyFollowUp = totalMonthlyFollowUp;
                        underCallback();
                    })

                }, cb)
            }

            F.Parallel([
                queryForEachSalesData,
            ], () => {
                callback();
            })

        }, cb)

    }

    F.Serial([
        salesmanList,
        searchUnderSales,
        queryForEachSalesRelated,
    ], () => {
        RES.successResponse(res, resultData);
    })


}